package com.ssm.service.manager;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.ssm.common.ImpoerModelUtil;
import com.ssm.common.util.layui.LayuiUnit;
import com.ssm.mapper.activiti.manager.ProcessManagerMapper;
import com.ssm.vo.activiti.manager.BaseManagerQueryVo;
import com.ssm.vo.activiti.manager.ProcessDefineModel;
import org.activiti.editor.constants.ModelDataJsonConstants;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Model;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.List;

@Service
public class ProcessManagerService {
    @Resource
    private ProcessManagerMapper processManagerMapper;
    @Resource
    private RepositoryService repositoryService;
    @Resource
    private ProcessEngine processEngine;
    @Resource
    private ObjectMapper objectMapper;
    @Resource
    private ImpoerModelUtil impoerModelUtil;

    /**
     * 获取查询结果
     *
     * @param baseManagerQueryVo
     * @return
     */
    public LayuiUnit queryActivitiProcessDefine(BaseManagerQueryVo baseManagerQueryVo) {
        String name = baseManagerQueryVo.getName();
        if (StringUtils.isNotEmpty(name)) {
            baseManagerQueryVo.setName("%" + name + "%");
        }
        String key = baseManagerQueryVo.getKey();
        if (StringUtils.isNotEmpty(key)) {
            baseManagerQueryVo.setKey("%" + key + "%");
        }

        Integer page = baseManagerQueryVo.getPage();
        Integer limit = baseManagerQueryVo.getLimit();
        baseManagerQueryVo.setBegincount((page - 1) * limit + 1);
        baseManagerQueryVo.setEndcount(page * limit);

        return LayuiUnit.data(processManagerMapper.getProcessDefineCount(baseManagerQueryVo)
                , processManagerMapper.getProcessDefineList(baseManagerQueryVo));
    }

    /**
     * 流程转化为可编辑模型
     *
     * @param processDefineModel
     */
    public String changeProcessToModel(ProcessDefineModel processDefineModel) {
        Model modelData = repositoryService.newModel();
        // 初始化Model
        ObjectNode modelObjectNode = objectMapper.createObjectNode();
        modelObjectNode.put(ModelDataJsonConstants.MODEL_NAME, processDefineModel.getName());
        modelObjectNode.put(ModelDataJsonConstants.MODEL_REVISION, 1);
        modelObjectNode.put(ModelDataJsonConstants.MODEL_DESCRIPTION, processDefineModel.getDescription());
        modelData.setMetaInfo(modelObjectNode.toString());
        modelData.setName(processDefineModel.getName());
        modelData.setKey(processDefineModel.getKey());
        // 保存模型
        repositoryService.saveModel(modelData);

        String deploymentId = processDefineModel.getDeploymentId();
        String processDefineResourceName = null;
        // 通过deploymentId取得某个部署的资源的名称
        List<String> resourceNames = processEngine.getRepositoryService().getDeploymentResourceNames(deploymentId);
        if (resourceNames != null && resourceNames.size() > 0) {
            for (String temp : resourceNames) {
                if (temp.indexOf(".xml") > 0) {
                    processDefineResourceName = temp;
                }
            }
        }

        /*
         * 读取资源
         * deploymentId:部署的id
         * resourceName：资源的文件名
         */
        InputStream bpmnStream = processEngine.getRepositoryService()
                .getResourceAsStream(deploymentId, processDefineResourceName);
        impoerModelUtil.creatModelByImpoutStream(bpmnStream, modelData.getId());

        return modelData.getId();

    }

    /**
     * 删除部署流程（单个删除与批量删除）
     *
     * @param deploymentIds ：被删除部署流程ID
     * @param deleteFlag    : 是否级联删除，1.true级联删除；2.false非级联删除
     */
    public void deleteProcessDeployments(String deploymentIds, boolean deleteFlag) {
        String[] deploymentIdArray = deploymentIds.split(",");
        for (String deploymentId : deploymentIdArray) {
            if (StringUtils.isNotEmpty(deploymentId)) {
                processEngine.getRepositoryService().deleteDeployment(deploymentId, deleteFlag);
            }
        }
    }

}
